﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Agro.Models;
using SN.Data;

namespace Agro.Services
{
    public   class ReportAnalyse:BaseService, IReportAnalyse
    {
        public T_Report GetReport(string reportid)
        {
            T_Report model = DB.From<T_Report>().Where(T_Report._.Report_ID == reportid).ToSingle();
            return model;

        }
        //获得报表指标
        public DataTable GetReportTarget(string ReportId)
        {
            Field[] filed = new Field[] {(new Field("'3'")).As("ID"), T_ZBZD._.ZBZD_Dimension.As("NAME"),(new Field("'1'")).As("PARENTID")};
            DataTable TargetDt = DB.From<T_ZBZD>().Where(T_ZBZD._.ZBZD_ReportID == ReportId).Select(filed).Distinct().ToDataTable();
            return TargetDt;
        }
        public DataTable GetReportLatitude(string ReportId)
        {
            Field[] filed = new Field[] { (new Field("'4'")).As("ID"), T_ZBZD._.ZBZD_Index.As("NAME"), (new Field("'2'")).As("PARENTID") };
            DataTable LatitudeDT = DB.From<T_ZBZD>().Where(T_ZBZD._.ZBZD_ReportID == ReportId).Select(filed).Distinct().ToDataTable();
            return LatitudeDT;
        }


        /// <summary>
        /// 报表统计
        /// </summary>
        /// <param name="reportid">报表ID</param>
        /// <param name="zb">指标</param>
        /// <param name="wd">纬度</param>
        /// <param name="dwid">单位编号</param>
        /// <returns>将结果以html表格形式拼成的字符串传回</returns>
        public string ReportCompute(string reportid,string zb, string wd,string dwid)
        {
            DataTable ZbTable = DB.From<T_ZBZD>().Where(T_ZBZD._.ZBZD_ReportID == reportid).ToDataTable();

            WhereClip wclip=T_ZBSJ._.ZBSJ_ReportID==reportid;
            if(!string.IsNullOrEmpty(dwid))
            {
                wclip=wclip&&T_ZBSJ._.ZBSJ_DWID.In(dwid);
            }

            DataTable ZBSJTable = DB.From<T_ZBSJ>().Where(wclip).ToDataTable();




            zb = zb.Remove(zb.Length - 1) ;
            wd = wd.Remove(wd.Length - 1) ;

            string[] zbarr = zb.Split(',');
            string[] wdarr = wd.Split(',');
            int zbcount=zbarr.Length;
            int wdcount=wdarr.Length;
           // DataTable dtResult = ZbTable.Clone();

            StringBuilder Builder = new StringBuilder();
            Builder.Append("<table id='TableMain'>");
            Builder.Append("<tr><td class='tdcenter'>指标</td>");
            for (int i = 0; i < zbcount; i++)
            {
                Builder.AppendFormat("<td class='tdcenter'>{0}</td>", zbarr[i]);
            }


            Builder.Append("</tr>");


            for (int j = 0; j < wdcount; j++)
            {

                Builder.AppendFormat("<tr><td>{0}</td>", wdarr[j]);
                for (int i = 0; i < zbcount; i++)
                {
                    DataRow[] rows = ZbTable.Select("zbzd_index='" + wdarr[j] + "' and zbzd_dimension='" + zbarr[i] + "'");
                    if (rows.Length > 0)
                    {
                        DataRow[] zbrows = ZBSJTable.Select("ZBSJ_ZBBH='" + rows[0]["ZBZD_ZBBH"] + "'");
                        if (zbrows.Length > 0)
                            Builder.AppendFormat("<td>{0}</td>", zbrows[0]["ZBSJ_VALUE"]);
                        else
                            Builder.AppendFormat("<td>{0}</td>", "");
                    }
                    else
                        Builder.AppendFormat("<td>{0}</td>", "");
                    
                }

                Builder.Append("</tr>");
            }

            Builder.Append("</table>");


            return Builder.ToString();
        }
        public string ReportCompute(string reportid, string year, string month1, string month2, string zb, string wd, string[] dwid)
        {
            zb = zb.Remove(zb.Length - 1);
            wd = wd.Remove(wd.Length - 1);

            string[] zbarr = zb.Split(',');
            string[] wdarr = wd.Split(',');
            int zbcount = zbarr.Length;
            int wdcount = wdarr.Length;
            // DataTable dtResult = ZbTable.Clone();


            T_Report report = GetEntity<T_Report>(T_Report._.Report_ID == reportid);
            WhereClip wclip = T_ZBSJ._.ZBSJ_ReportID == reportid;


            StringBuilder Builder = new StringBuilder();

            string par = "";
            switch (report.Report_Cycle)
            {
                case "01":
                    par = "月";
                    Builder.AppendFormat("<div style='padding:10px'>查询年度:{0}&nbsp;&nbsp;&nbsp;期间:{1}{3}至{2}{3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>", year, month1, month2, par);
                    wclip = wclip && T_ZBSJ._.ZBSJ_MONTH.Between(month1.PadLeft(2, '0'), month2.PadLeft(2, '0'));
                    break;
                case "02":
                    par = "季度";
                    if (int.Parse(month1) > 12)
                    {
                        month1 = (int.Parse(month1) - 12).ToString();
                        month2 = (int.Parse(month2) - 12).ToString();
                    }
                    Builder.AppendFormat("<div style='padding:10px'>查询年度:{0}&nbsp;&nbsp;&nbsp;期间:{1}{3}至{2}{3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>", year, month1, month2, par);
                    wclip = wclip && T_ZBSJ._.ZBSJ_MONTH.Between(month1.PadLeft(2, '0'), month2.PadLeft(2, '0'));
                    break;
                case "03":
                    Builder.AppendFormat("<div style='padding:10px'>查询年度:{0}&nbsp;&nbsp;&nbsp;</div>", year);
                    break;
            }






            //StringBuilder Builder = new StringBuilder();
            //string par = "月";
            //if (month1!="null" && month2!="null")
            //{
            //    if (int.Parse(month1) > 12)
            //    {
            //        par = "季度";
            //        month1 = (int.Parse(month1) - 12).ToString();
            //        month2 = (int.Parse(month2) - 12).ToString();
            //    }
            //}
            //else
            //{
            //    month1 = "";
            //    month2 = "";
            //    par = "";
            //}
            //Builder.AppendFormat("<div style='padding:10px'>查询年度:{0}&nbsp;&nbsp;&nbsp;期间:{1}{3}至{2}{3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div>", year, month1, month2, par);
            Builder.Append("<div style='padding:10px;'>");
            Builder.Append("<table id='TableMain'>");
          

            DataTable ZbTable = DB.From<T_ZBZD>().Where(T_ZBZD._.ZBZD_ReportID == reportid).ToDataTable();//查找指标
            ISourceList<T_Organization> orglist = DB.From<T_Organization>().Where(T_Organization._.Organization_ID.In(dwid)).ToList();


            if (dwid.Length > 0)
            {
                wclip = wclip && T_ZBSJ._.ZBSJ_DWID.In(dwid);
                wclip = wclip && T_ZBSJ._.ZBSJ_YEAR == year;
                //if (month1 != "null" && month2 != "null")
                //    wclip = wclip && T_ZBSJ._.ZBSJ_MONTH.Between(int.Parse(month1) < 10 ? "0" + month1 : month1, int.Parse(month2) < 10 ? "0" + month2 : month2);
            }

            DataTable ZBSJTable = DB.From<T_ZBSJ>().Where(wclip).ToDataTable();

            Builder.Append("<tr>");
            if (orglist.Count > 1)
            {
                Builder.Append("<td class='tdcenter' sx='org_title'></td>");
            }
            Builder.Append("<td class='tdcenter' sx='wd_title'></td>");
            for (int i = 0; i < zbcount; i++)
            {
                Builder.AppendFormat("<td class='tdcenter' sx='zb' zbname='{0}'>{0}</td>", zbarr[i]);
            }


            Builder.Append("</tr>");


            foreach (T_Organization detail in orglist)
            {

                for (int j = 0; j < wdcount; j++)
                {
                    if (orglist.Count > 1)
                    {
                        if (j == 0)//每个org的首行wd值 进行合并
                        {
                            Builder.AppendFormat("<tr><td rowspan={0} sx='org'>{1}</td>", wdcount, detail.Organization_Name);
                        }
                        Builder.AppendFormat("<td sx='wd' wdname='{1}:{0}'>{0}</td>", wdarr[j], detail.Organization_Name);
                    }
                    else
                    {
                        Builder.AppendFormat("<tr><td  sx='wd' wdname='{0}'>{0}</td>", wdarr[j]);
                    }
                    for (int i = 0; i < zbcount; i++)
                    {
                        DataRow[] rows = ZbTable.Select("zbzd_index='" + wdarr[j] + "' and zbzd_dimension='" + zbarr[i] + "'");
                        if (rows.Length > 0)
                        {
                            DataRow[] zbrows = ZBSJTable.Select("ZBSJ_ZBBH='" + rows[0]["ZBZD_ZBBH"] + "' and ZBSJ_DWID='" + detail.Organization_ID + "'");

                            if (zbrows.Length > 0)
                            {
                                double d = 0;
                                double value;
                                string m = string.Empty;
                                foreach (DataRow row in zbrows)
                                {

                                    if (double.TryParse(row["ZBSJ_VALUE"].ToString(), out value))//判断是否数字还是字符串，否则出错。
                                    {
                                        if (value == 0)
                                            m += "";
                                        else
                                            m += row["ZBSJ_VALUE"].ToString();
                                    }
                                    else 
                                    {
                                        m = m + row["ZBSJ_VALUE"].ToString() + "";
                                    }
                                }
                                Builder.AppendFormat("<td class='tdcenter' sx='data'>{0}</td>", m);
                                //Builder.AppendFormat("<td>{0}{1}</td>", d, m);
                            }
                            else 
                                Builder.AppendFormat("<td class='tdcenter' sx='data'>{0}</td>", "");
                        }
                        else
                            Builder.AppendFormat("<td class='tdcenter' sx='data'>{0}</td>", "");

                    }

                    Builder.Append("</tr>");
                }

            }
            Builder.Append("</table>");
            Builder.Append("</div>");
            return Builder.ToString();
           
        }
       

    }
}
